<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sell:sell:add']"
        >新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sellList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="订单编号" align="center" prop="sn" />
      <el-table-column label="下单用户" align="center" prop="ownerName" />
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="实付金额" align="center" prop="payPrice" />
      <el-table-column label="订单状态" align="center" prop="status" />
      <el-table-column label="支付状态" align="center" prop="paymentStatus" />
      <el-table-column label="销售渠道" align="center" prop="source" />
<!--      <el-table-column label="会员id/企业id/第三方用户id" align="center" prop="ownerId" />-->
<!--      <el-table-column label="会员名称/企业名称/第三方用户名称" align="center" prop="ownerName" />-->
<!--      <el-table-column label="会员手机号/企业手机号/第三方用户手机号" align="center" prop="ownerMobile" />-->

<!--      <el-table-column label="仓库id" align="center" prop="warehouseId" />-->

<!--      <el-table-column label="部门id" align="center" prop="deptId" />-->

<!--      <el-table-column label="销售经理id" align="center" prop="marketingId" />-->
<!--      <el-table-column label="销售经理名称" align="center" prop="marketingName" />-->
<!--      <el-table-column label="销售金额" align="center" prop="totalPrice" />-->
<!--      <el-table-column label="优惠金额" align="center" prop="discountPrice" />-->
<!--      <el-table-column label="税额" align="center" prop="taxPrice" />-->

<!--      <el-table-column label="定金金额" align="center" prop="depositPrice" />-->
<!--      <el-table-column label="附件" align="center" prop="attachment" />-->
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
<!--      <el-table-column label="订单类型" align="center" prop="type" />-->
<!--      <el-table-column label="订单来源" align="center" prop="source" />-->
<!--      <el-table-column label="订单来源id" align="center" prop="sourceId" />-->
<!--      <el-table-column label="配送方式" align="center" prop="deliveryType" />-->
<!--      <el-table-column label="物流配送地区id集合" align="center" prop="shipRegionIds" />-->
<!--      <el-table-column label="物流配送地区名称集合" align="center" prop="shipRegionNames" />-->
<!--      <el-table-column label="物流配送详细地址" align="center" prop="shipAddress" />-->
<!--      <el-table-column label="自提门店id" align="center" prop="storeId" />-->
<!--      <el-table-column label="自提门店名称" align="center" prop="storeName" />-->
<!--      <el-table-column label="是否已出库" align="center" prop="warehouseOutFlag" />-->
<!--      <el-table-column label="出库单id" align="center" prop="warehouseOutId" />-->
<!--      <el-table-column label="是否已发货" align="center" prop="shipFlag" />-->
<!--      <el-table-column label="发货时间" align="center" prop="shipTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.shipTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="物流公司id" align="center" prop="logisticsCompanyId" />-->
<!--      <el-table-column label="物流公司名称" align="center" prop="logisticsCompanyName" />-->
<!--      <el-table-column label="物流单号" align="center" prop="logisticsTrackingNumber" />-->
<!--      <el-table-column label="是否删除" align="center" prop="deleted" />-->
<!--      <el-table-column label="创建者" align="center" prop="creator" />-->
<!--      <el-table-column label="更新者" align="center" prop="updater" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- Submit/Withdraw button -->
          <el-button
            v-if="scope.row.status !=='已审核'"
            size="mini"
            type="text"
            :icon="scope.row.status === '待提交' ? 'el-icon-upload2' : 'el-icon-refresh-left'"
            @click="scope.row.status === '待提交' ? handleSubmit(scope.row) : handleWithdraw(scope.row)"
            v-hasPermi="['sell:sell:edit']"
          >{{ scope.row.status === '待提交' ? '提交' : '撤回' }}</el-button>

          <!-- Edit/Audit button -->
          <el-button
            v-if="scope.row.status !== '已审核'"
            size="mini"
            type="text"
            :icon="scope.row.status === '待审核' ? 'el-icon-edit' : 'el-icon-check'"
            @click="scope.row.status === '待审核' ? handleAudit(scope.row) : handleUpdate(scope.row)"
            v-hasPermi="['sell:sell:edit']"
          >{{ scope.row.status === '待审核' ? '审核' : '编辑' }}</el-button>

          <!-- Set as Paid button - only show when status is not '已支付' -->
          <el-button
            v-if="scope.row.paymentStatus !== '已支付'"
            size="mini"
            type="text"
            icon="el-icon-money"
            @click="handlePay(scope.row)"
            v-hasPermi="['sell:sell:edit']"
          >设为已支付</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改零售管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-select
            v-model="form.warehouseName"
            placeholder="请选择仓库名称"
            clearable
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择下单时间"
            :default-value="new Date()">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员" prop="ownerName">
          <el-select
            v-model="form.ownerName"
            placeholder="请选择会员"
            clearable
          >
            <el-option
              v-for="owner in ownerOptions"
              :key="owner.id"
              :label="owner.name"
              :value="owner.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属部门">
          <el-cascader
            v-model="form.deptId"
            :options="deptTree"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择所属部门"
            @change="handleDeptChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="实付金额" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入付款金额"/>
        </el-form-item>
        <el-form-item label="销售渠道" prop="source">
          <el-select v-model="form.source" placeholder="请输入销售渠道">
            <el-option label="平台" value="平台" />
            <el-option label="线下销售" value="线下销售" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-table :data="form.productList" border style="width: 100%; margin-bottom: 20px;">-->
<!--          <el-table-column prop="productName" label="商品名称" width="150"></el-table-column>-->
<!--          <el-table-column prop="specification" label="规格"></el-table-column>-->
<!--          <el-table-column prop="stock" label="库存" width="100"></el-table-column>-->
<!--          <el-table-column label="数量" width="100">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input-number-->
<!--                v-model="scope.row.quantity"-->
<!--                :min="1"-->
<!--                size="mini"-->
<!--                @change="calculateAmount(scope.row)">-->
<!--              </el-input-number>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="单价" width="120">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input-->
<!--                v-model="scope.row.unitPrice"-->
<!--                @blur="calculateAmount(scope.row)">-->
<!--              </el-input>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="金额" width="120">-->
<!--            <template slot-scope="scope">-->
<!--              {{ scope.row.amount || '0.00' }}-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="操作" width="80">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="danger"-->
<!--                @click="removeProduct(scope.$index)">-->
<!--                删除-->
<!--              </el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->

<!--        <el-button @click="openProductDialog">添加商品</el-button>-->

<!--        &lt;!&ndash; 商品选择对话框 &ndash;&gt;-->
<!--        <el-dialog title="选择商品" :visible.sync="showProductDialog" width="80%">-->
<!--          <el-table-->
<!--            :data="productOptions"-->
<!--            @selection-change="handleProductSelection"-->
<!--            style="width: 100%">-->
<!--            <el-table-column type="selection" width="55"></el-table-column>-->
<!--            <el-table-column prop="name" label="商品名称"></el-table-column>-->
<!--            <el-table-column prop="specification" label="规格"></el-table-column>-->
<!--            <el-table-column prop="stock" label="库存"></el-table-column>-->
<!--          </el-table>-->
<!--          <div slot="footer" class="dialog-footer">-->
<!--            <el-button @click="showProductDialog = false">取消</el-button>-->
<!--            <el-button type="primary" @click="confirmAddProducts">确定</el-button>-->
<!--          </div>-->
<!--        </el-dialog>-->




<!--        <el-form-item label="销售经理名称" prop="marketingName">-->
<!--          <el-input v-model="form.marketingName" placeholder="请输入销售经理名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="销售金额" prop="totalPrice">-->
<!--          <el-input v-model="form.totalPrice" placeholder="请输入销售金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="优惠金额" prop="discountPrice">-->
<!--          <el-input v-model="form.discountPrice" placeholder="请输入优惠金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="税额" prop="taxPrice">-->
<!--          <el-input v-model="form.taxPrice" placeholder="请输入税额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="应付金额" prop="payPrice">-->
<!--          <el-input v-model="form.payPrice" placeholder="请输入应付金额" />-->
<!--        </el-form-item>-->

        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSell, getSell, delSell, addSell, updateSell,updateStatus,updatePaymentStatus,listProduct   } from "@/api/sell/sell";
import { listWarehouse } from "@/api/system/warehouse";
import {listMember} from '@/api/system/member';
import {getDeptTree} from "@/api/procurementmanagement/plan";
export default {
  name: "Sell",
  data() {
    return {
      showProductDialog: false,
      productOptions: [],
      selectedProducts: [],
      warehouseOptions:[],
      onwerOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 零售管理表格数据
      sellList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        status: null,
        paymentStatus: null,
        paymentTime: null,
        ownerId: null,
        ownerName: null,
        ownerMobile: null,
        orderTime: null,
        warehouseId: null,
        warehouseName: null,
        deptId: null,
        deptName: null,
        marketingId: null,
        marketingName: null,
        totalPrice: null,
        discountPrice: null,
        taxPrice: null,
        payPrice: null,
        depositPrice: null,
        attachment: null,
        type: null,
        source: null,
        sourceId: null,
        deliveryType: null,
        shipRegionIds: null,
        shipRegionNames: null,
        shipAddress: null,
        storeId: null,
        storeName: null,
        warehouseOutFlag: null,
        warehouseOutId: null,
        shipFlag: null,
        shipTime: null,
        logisticsCompanyId: null,
        logisticsCompanyName: null,
        logisticsTrackingNumber: null,
        deleted: null,
        creator: null,
        updater: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseOptions(); // 获取仓库和部门数据
    this.getOwnerOptions();
    this.getProductOptions();
  },
  methods: {

    handleProductSelection(selection) {
      this.selectedProducts = selection;
    },
    handleSubmit(row) {
      this.$modal.confirm('确认要提交该订单吗？').then(() => {
        const data = {
          id: row.id,
          status: '待审核' // 假设提交后状态变为"待审核"
        };
        updateStatus(data).then(response => {
          this.$modal.msgSuccess("提交成功");
          this.getList();
        });
      }).catch(() => {});
    },
    openProductDialog() {
      this.showProductDialog = true;
      this.getProductOptions();
    },
    handleDeptChange(value) {
      if (value.length > 0) {
        // 获取选中的最后一级部门的 ID
        const deptId = value[value.length - 1];
        // 根据 ID 查找对应的部门对象
        const selectedDept = this.findDeptById(this.deptTree, deptId);
        if (selectedDept) {
          this.form.deptId = selectedDept.id; // 保存子部门的 ID
          this.form.deptName = selectedDept.name; // 保存子部门的名称
          console.log(this.form.deptName,this.form.deptId);
        }
      } else {
        this.form.deptId = null;
        this.form.deptName = null;
      }
    },
    findDeptById(tree, id) {
      for (let dept of tree) {
        if (dept.id === id) {
          return dept; // 如果找到匹配的 ID，返回该部门对象
        }
        if (dept.children && dept.children.length > 0) {
          const result = this.findDeptById(dept.children, id); // 递归查找子部门
          if (result) return result;  // 如果在子部门中找到，返回结果
        }
      }
      return null; // 如果未找到，返回 null
    },
    getDeptTree() {
      getDeptTree().then(response => {
        console.log(response.data)
        this.deptTree = response.data;
      });
    },

    /** 撤回订单 */
    handleWithdraw(row) {
      this.$modal.confirm('确认要撤回该订单吗？').then(() => {
        const data = {
          id: row.id,
          status: '待提交' // 撤回后状态变为"待提交"
        };
        updateStatus(data).then(response => {
          this.$modal.msgSuccess("撤回成功");
          this.getList();
        });
      }).catch(() => {});
    },
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    getOwnerOptions() {
      listMember().then(response => {
        response.rows.forEach(owner => {
          owner.ownerName = owner.name;
        });
        this.ownerOptions = response.rows;
      });
    },
    confirmAddProducts() {
      if (!this.form.productList) {
        this.form.productList = [];
      }

      this.selectedProducts.forEach(product => {
        const existingIndex = this.form.productList.findIndex(
          item => item.productId === product.id
        );

        if (existingIndex >= 0) {
          // 商品已存在，增加数量
          this.form.productList[existingIndex].quantity += 1;
          this.calculateAmount(this.form.productList[existingIndex]);
        } else {
          // 添加新商品
          this.form.productList.push({
            productId: product.id,
            productName: product.name || product.productName,
            specification: product.specification || product.model,
            stock: product.stock || product.inventory,
            quantity: 1,
            unitPrice: product.price || product.unitPrice,
            amount: (product.price || product.unitPrice || 0) * 1
          });
        }
      });

      this.showProductDialog = false;
      this.selectedProducts = [];
      this.calculateTotal();
    },

    /** 设为已支付 */
    handlePay(row) {
      this.$modal.confirm('确认该订单已支付吗？').then(() => {
        const data = {
          id: row.id,
          paymentStatus: '已支付'
        };
        updatePaymentStatus(data).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        }).catch(error => {
          this.$modal.msgError("操作失败：" + error.message);
        });
      }).catch(() => {});
    },

    /** 审核订单 */
    handleAudit(row) {
      this.$modal.confirm('确认审核通过该订单吗？').then(() => {
        const data = {
          id: row.id,
          status: '已审核' // 审核后状态变为"已审核"
        };
        updateStatus(data).then(response => {
          this.$modal.msgSuccess("审核成功");
          this.getList();
        });
      }).catch(() => {});
    },
    /** 查询零售管理列表 */
    getList() {
      this.loading = true;
      listSell(this.queryParams).then(response => {
        this.sellList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productList: [],
        id: null,
        sn: null,
        status: "待提交",
        paymentStatus: "未支付",
        paymentTime: null,
        ownerId: null,
        ownerName: null,
        ownerMobile: null,
        orderTime: null,
        warehouseId: null,
        warehouseName: null,
        deptId: null,
        deptName: null,
        marketingId: null,
        marketingName: null,
        totalPrice: null,
        discountPrice: null,
        taxPrice: null,
        payPrice: null,
        depositPrice: null,
        attachment: null,
        remark: null,
        type: null,
        source: null,
        sourceId: null,
        deliveryType: null,
        shipRegionIds: null,
        shipRegionNames: null,
        shipAddress: null,
        storeId: null,
        storeName: null,
        warehouseOutFlag: null,
        warehouseOutId: null,
        shipFlag: null,
        shipTime: null,
        logisticsCompanyId: null,
        logisticsCompanyName: null,
        logisticsTrackingNumber: null,
        deleted: null,
        createTime: null,
        updateTime: null,
        creator: null,
        updater: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.getWarehouseOptions();
      this.getOwnerOptions();
      this.getDeptTree();
      this.getProductOptions();
      this.title = "添加零售管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSell(id).then(response => {
        this.form = response.data;
        if (!this.form.productList) {
          this.form.productList = [];
        }
        this.open = true;
        this.title = "修改零售管理";
        this.getWarehouseOptions();
        this.getDeptTree();
        this.getProductOptions();
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.id != null) {
        // 如果是修改订单状态（如提交/撤回/审核），调用 updateStatus
        if (this.form.status) {
          updateStatus(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
        // 如果是修改支付状态，调用 updatePaymentStatus
        else if (this.form.paymentStatus) {
          updatePaymentStatus(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      } else {
        // 新增订单
        addSell(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    addProduct() {
      if (!this.form.productList) {
        this.form.productList = [];
      }
      this.form.productList.push({
        productId: null,
        productName: '',
        specification: '',
        stock: 0,
        quantity: 1,
        unitPrice: 0,
        amount: 0
      });
    },
    handleProductChange(row) {
      const product = this.productOptions.find(p => p.id === row.productId);
      if (product) {
        row.productName = product.name || product.productName; // 根据实际字段调整
        row.specification = product.specification || product.model;
        row.stock = product.stock || product.inventory;
        row.unitPrice = product.price || product.unitPrice;
        this.calculateAmount(row);
      }
    },
    calculateAmount(row) {
      row.amount = (row.quantity * row.unitPrice).toFixed(2);
      this.calculateTotal();
    },

    // 计算总金额
    calculateTotal() {
      if (!this.form.productList) return;

      const total = this.form.productList.reduce(
        (sum, item) => sum + (parseFloat(item.amount) || 0),
        0
      );

      this.form.totalPrice = total;
      this.form.payPrice = total; // 假设支付金额与总金额相同
    },

    // 加载商品选项
    getProductOptions() {
      this.$axios.get('/sell/sell/product/list').then(response => {
        this.productOptions = response.rows || response.data || [];
      }).catch(error => {
        console.error("获取商品列表失败:", error);
        this.$message.error("获取商品列表失败");
      });
    },

    removeProduct(index) {
      this.form.productList.splice(index, 1);
      this.calculateTotal();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除零售管理编号为"' + ids + '"的数据项？').then(function() {
        return delSell(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sell/sell/export', {
        ...this.queryParams
      }, `sell_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
